// 登录注册切换DOM对象
const login = document.querySelector('.login')
const sign = document.querySelector('.sign')
const borderLogin = document.querySelector('.borderLogin')
// 输入框DOM对象
const inputs = document.querySelectorAll('.enter input')
// 确认按钮
const loginSure = document.querySelector('.loginSure')
// 正则表达式
const reg = /^[0-9a-zA-Z]{1,12}$/

let statusLog = 1    //设1为登录，0为注册

// 登录/注册切换
login.addEventListener('click', () => {
  inputs[0].value = inputs[1].value = ''    //清空输入框内容
  borderLogin.style.left = 0 + 'px'
  inputs[0].placeholder = ' 帐号长度不超过12位'
  inputs[1].placeholder = ' 密码必须以12位以内的数字、字母搭配'
  loginSure.innerHTML = '登录'
  statusLog = 1
})

sign.addEventListener('click', () => {
  inputs[0].value = inputs[1].value = ''
  borderLogin.style.left = 92 + 'px'
  inputs[0].placeholder = ' 请输入12位以内的帐号'
  inputs[1].placeholder = ' 请输入12以内包含数字、字母的密码'
  loginSure.innerHTML = '注册'
  statusLog = 0
})

function logCheck() {
  // 获取帐号密码
  const countNumber = inputs[0].value
  const password = inputs[1].value
  const identification = document.querySelector('.whichPosition input:checked').value   //获取身份
  console.log(countNumber, password, identification);
  const reg = /^[0-9a-zA-Z]{1,12}$/     //正则表达式
  if (!countNumber.length || !password.length) {
    alert('帐号与密码不能为空')
    return
  } else if (!reg.test(countNumber) || !reg.test(password)) {
    alert('帐号或密码不符合规范')
    return
  }
  axios({
    url: 'http://127.0.0.1:8080/CountLog',
    params: {
      countNumber,
      password,
      identification
    }
  }).then(() => {
    if (identification === '1' || identification === '2') {
      location.href = '../StudentAndTeacher/Major/index.html'
    } else {
      location.href = '../Root/Major/index.html'
    }
  }).catch(() => {
    alert('账户不存在或密码错误')
  })
}

function signCheck() {
  const countNumber = inputs[0].value
  const password = inputs[1].value
  const identification = document.querySelector('.whichPosition input:checked').value   //获取身份
  if (!reg.test(countNumber) || !reg.test(password)) {
    alert('帐号或密码不符合规范')
    return
  }
  axios({
    url: 'http://127.0.0.1:8080/CountSign',
    method: 'POST',
    data: {
      countNumber,
      password,
      identification
    }
  }).then(() => {
    alert('账户注册成功')
  }).catch(() => {
    alert('账户已存在')
  })
}

loginSure.addEventListener('click', (e) => {
  e.preventDefault()
  if (statusLog === 1) {
    logCheck()
  } else {
    signCheck()
  }
})